//
//  DetailViewController.m
//  xiaowanTravel
//
//  Created by wyzcWLB on 16/10/5.
//  Copyright © 2016年 wyzcWLB. All rights reserved.
//

#import "DetailViewController.h"
#import <AFNetworking.h>
#import "mndidiModel.h"
#import "HotCityCell.h"
#import <UIImageView+WebCache.h>
#import "DiscountCell.h"
#import "HeadCollectionReusableView.h"
#import "DisCollectionReusableView.h"

@interface DetailViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSMutableArray *adArray;//广告栏
@property(nonatomic,strong)NSMutableArray *hotcityArray;
@property(nonatomic,strong)NSMutableArray *discountArray;
@property(nonatomic,strong)NSString *cname;
@property(nonatomic,strong)NSString *ename;
@property(nonatomic,strong)NSString *info;

@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _dataArray = [[NSMutableArray alloc]init];
    _adArray = [[NSMutableArray alloc]init];
    _hotcityArray = [[NSMutableArray alloc]init];
    _discountArray = [[NSMutableArray alloc]init];
    [self creatScorllView];
    [self requestData];
}

-(void)requestData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //申明返回的结果是json类型
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *str1 = @"http://open.qyer.com/qyer/footprint/country_detail?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&country_id=%ld%@";
    NSString *str2 = @"&lat=40.03622574273529&lon=116.363834514835&oauth_token=2c8a27f98da55363b7f5ca09940dc14c&page=1&track_app_channel=App%2520Store&track_app_version=6.8&track_device_info=iPhone7%2C1&track_deviceid=7B6FA080-F9FB-44C1-B932-401CD69CD5D2&track_os=ios%25209.1&track_user_id=6971539&v=1";
    NSString *url = [NSString stringWithFormat:str1,self.DetialID,str2];
    
    [manager GET:url parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        
        mndidiModel *detailModel=[[mndidiModel alloc]mj_setKeyValues:dic];
        
        _cname = detailModel.data.cnname;
        _ename = detailModel.data.enname;
        _info = detailModel.data.entryCont;
        _adArray = detailModel.data.photos;
        
        NSArray *array = detailModel.data.hot_city;
        
        for (NSDictionary *dic in array)
        {
            [_hotcityArray addObject:dic];
        }
        NSArray *disArray = detailModel.data.discount;
        for (NSDictionary *discount in disArray) {
            [_discountArray addObject:discount];
        }
        
        [_collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
   
}
-(void)creatScorllView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
    
    [_collectionView  registerNib:[UINib nibWithNibName:@"HotCityCell" bundle:nil] forCellWithReuseIdentifier:@"HotCityCell"];
    [_collectionView  registerNib:[UINib nibWithNibName:@"DiscountCell" bundle:nil] forCellWithReuseIdentifier:@"DiscountCell"];
    [_collectionView registerClass:[HeadCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
               withReuseIdentifier:@"HeadCollectionReusableView"];
    [_collectionView registerClass:[DisCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
               withReuseIdentifier:@"DisCollectionReusableView"];
    
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section==0) {
        return _hotcityArray.count;
    }else{
        return _discountArray.count;
    }
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        HotCityCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HotCityCell" forIndexPath:indexPath];
        HotcityModel *model = _hotcityArray[indexPath.row];
        [cell.imageV sd_setImageWithURL:[NSURL URLWithString:model.photo]];
        cell.imageV.layer.cornerRadius = 8;
        cell.imageV.layer.masksToBounds = YES;
        cell.cname.text = model.cnname;
        cell.ename.text = model.enname;
        return cell;
        
    }else
    {
        DiscountCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"DiscountCell" forIndexPath:indexPath];
        DiscountModel *model = _discountArray[indexPath.row];
        [cell.icon sd_setImageWithURL:[NSURL URLWithString:model.photo]];
        cell.icon.layer.cornerRadius = 5;
        cell.icon.layer.masksToBounds = YES;
        cell.title.text = model.title;
        cell.discount.text = model.priceoff;
       
       // <em>1999</em>元起

        NSString *string = model.price;
        NSRange startRange = [string rangeOfString:@"m>"];
        NSRange endRange = [string rangeOfString:@"</"];
        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
        NSString *result = [string substringWithRange:range];
        cell.price.text = [NSString stringWithFormat:@"%@元起", result];

        return cell;
    }

}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==0) {
        return CGSizeMake((Screen_Width-4)/2, 120*(Screen_Height/667.0));
    }else{
        return CGSizeMake(Screen_Width-4, 100*(Screen_Height/667.0));
    }
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 3;
}
//设置最小列间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

#pragma mark 设置头视图
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==0) {
        DisCollectionReusableView *disview = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"DisCollectionReusableView" forIndexPath:indexPath];
        disview.tag = 100;
        [self createAD];
        return disview;
    }else{
        HeadCollectionReusableView *head = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HeadCollectionReusableView" forIndexPath:indexPath];
        head.headTitle.text = @"超值自由行";
        return head;
    }
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section ==0) {
        return CGSizeMake(Screen_Width, 250*(Screen_Height/667.0));
    }else{
        return CGSizeMake(Screen_Width, 25*(Screen_Height/667.0));
    }
}

#pragma mark 实现代理方法
-(void)createAD
{
    DisCollectionReusableView *adview = (DisCollectionReusableView *)[self.view viewWithTag:100];
    adview.array = _adArray;
    adview.scrollView.contentSize = CGSizeMake(_adArray.count*Screen_Width, 250);
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(5, 10, 50, 50);
    [button1 setImage:[UIImage imageNamed:@"icon_trip_cancel"] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(btnLeftClick) forControlEvents:UIControlEventTouchUpInside];
    [adview addSubview:button1];
    for (UIView *subview in adview.scrollView.subviews)
    {
        [subview removeFromSuperview];//移除
    }
    //点击图片能够滑动,跳转
    for (int i=0; i<_adArray.count; i++) {
        
        UIImageView *imageV = [[UIImageView alloc]init];
        imageV.frame = CGRectMake(i*Screen_Width, 0, Screen_Width, 250);
        [imageV sd_setImageWithURL:[NSURL URLWithString:_adArray[i]]];
        [adview.scrollView addSubview:imageV];
        
        
        UILabel *cnameLabel = [self creatLabelWithText:_cname andWithFrame:CGRectMake(20+i*Screen_Width, 150, 100, 20) andWithFont:[UIFont systemFontOfSize:18] andColor:[UIColor whiteColor]];
        UILabel *enameLabel = [self creatLabelWithText:_ename andWithFrame:CGRectMake(20+i*Screen_Width, 170, 100, 20) andWithFont:[UIFont systemFontOfSize:16] andColor:[UIColor whiteColor]];
        UILabel *infoLabel = [self creatLabelWithText:_info andWithFrame:CGRectMake(20+i*Screen_Width, 200, Screen_Width-50, 50) andWithFont:[UIFont systemFontOfSize:16] andColor:[UIColor whiteColor]];
        [adview.scrollView addSubview:cnameLabel];
        [adview.scrollView addSubview:enameLabel];
        [adview.scrollView addSubview:infoLabel];
    }
    
}
-(void)btnLeftClick
{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(UILabel *)creatLabelWithText:(NSString *)text andWithFrame:(CGRect)frame andWithFont:(UIFont *)font andColor:(UIColor *)color
{
    UILabel *label = [[UILabel alloc]initWithFrame:frame];
    label.text = text;
    label.font = font;
    label.textColor = color;
    label.numberOfLines = 0;
    return label;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    DisCollectionReusableView *adview = (DisCollectionReusableView *)[self.view viewWithTag:100];
    CGFloat offsetY = adview.scrollView.contentOffset.y;
    
    if (offsetY < 0)
    {
        CGFloat scale = 1 - offsetY/100;
        adview.transform = CGAffineTransformMakeScale(scale, scale);
    }
}

@end
